﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LunchCommand.Models;
using System.Collections.Concurrent;

namespace LunchCommand.Services.Maps
{
    /// <summary>
    /// Caches the travel times for venues so that we don't spam Bing's servers
    /// </summary>
    internal static class VenueTravelCache
    {
        private static ConcurrentDictionary<Int32, VenueTravelTime> cache = new ConcurrentDictionary<Int32, VenueTravelTime>();

        internal static VenueTravelTime GetTravelTime(Lunch forLunch, Venue venue, String startAddress, IMapService service)
        {
            // Don't bother checking if we're an hour past lunch already
            if (forLunch.LunchTime > DateTime.Now.AddHours(1))
            {
                return new VenueTravelTime()
                {
                    Obtained = DateTime.Now
                };
            }

            var time = cache.GetOrAdd(venue.VenueID, x =>
            {
                return new VenueTravelTime()
                    {
                        TravelTime = service.GetTravelTime(startAddress, venue.Address),
                        Obtained = DateTime.Now
                    };
            });

            if ((DateTime.Now - time.Obtained).TotalMinutes >= 10)
            {
                time = cache[venue.VenueID] = new VenueTravelTime()
                {
                    TravelTime = service.GetTravelTime(startAddress, venue.Address),
                    Obtained = DateTime.Now
                };
            }

            return time;
        }
    }
}